#
#  Change	Date		Author			Description
# --------------------------------------------------------------------------------------------------------
#   001	        07-10-2013	Adam Dosch		Initial Release
#   002         07-14-2013      Adam Dosch              Added commented out functionality to turn any non
#                                                       comma-separated option value into a list as well.
#                                                       Working on adding BuildObject() class for build-daemon
#                                                       to handle build items received from queue
#   003         07-16-2013      Adam Dosch              Adding getCurrentBuildStatus() method to return the
#                                                       current build object in JSON
#   006         08-04-2013      Adam Dosch              Changed 'processed' build/queue JSON document option
#                                                       (which signified if item was processed or picked up by
#                                                       a build daemon) to 'pickedUp' instead
#

import sys
import platform

import os
import ConfigParser

import json
import datetime

class Config:
    
    def __init__(self, configFile="/etc/rbs.cfg"):
        """
        RBS Configuration file setup
        """
        
        # Validate if config file exists and can be read
        #if os.path.isfile(configFile):
        #    if os.access(configFile, os.R_OK):
        #        self.configFile = configFile
        #    else:
        #        raise Exception("Configuration file/path not accessible or readable by the uid/gid running this application.  Try again.")
        #else:
        #    raise Exception("Configuration file is not a file or does not exist.  Try again.")

        # Configuration file
        self.configFile = configFile

        # Setup ConfigParser object
        self.parserConfig = ConfigParser.ConfigParser()
        
        # Try to read/load configuration file
        self.loadConfiguration()

    def loadConfiguration(self):
        """
        Load or Re-load RBS Configuratoin
        """
        self.parserConfig.read(self.configFile)

    def getConfiguration(self, section):
        """
        Get and parse RBS configuration
        """
        config = {}
    
        options = self.parserConfig.options(section)
        
        # Put all the read-in options into a list
        for option in options:
            try:
                if "," in self.parserConfig.get(section, option):
                    config[option] = self.parserConfig.get(section, option).split(",")
                else:
                    config[option] = self.parserConfig.get(section, option)
                    #config[option] = [self.parserConfig.get(section, option)] -- list form
            except:
                config[option] = None
    
        return config

class BuildObject:
  #'id': <foo>, 
  #'package': 'ledaps'
  #'version: '1.2.1'
  #'release: '10'
  #'group': 'ESPA'
  #'ostype': 'el6',
  #'arch': 'x86_64',
  #'build': {
  #    'state': 'complete',
  #    'submittime': '2013-06-20 12:31:00',
  #    'starttime': '2013-06-20 12:33:33',
  #    'endtime': '2013-06-20 12:40:01',
  #    'log': 'big-long-fooooo'
  #    'server': 'serverName',
  #    'cksum': '3915528286',
  #    'bytes': 3848459
  # },
  # 'buildrelease': {
  #    'month': '06'
  #    'year': '2013'
  # },
  # 'repo': {
  #    'deploy': 'True',
  #    'location': '/data/repo/espa/el6/',
  #    'filename': 'ledaps-1.2.1-10.el6.x86_64.rpm'
  # }
  
    def __init__(self, queueItem):
        self.id = queueItem['_id']
        
        self.package = queueItem['package']
        self.version = None
        self.release = None
        self.group = None
        self.ostype = queueItem['ostype']
        self.arch = queueItem['ostype']
        
        self.build = queueItem['build']
        self.build['state'] = "created"
        self.build['server'] = platform.node()
        
        self.buildrelease = {}
        
        self.repo = queueItem['repo']
    
    def getCurrentBuildStatus(self):
        output = {'_id': self.id,
                  'package': self.package,
                  'version': self.version,
                  'release': self.release,
                  'group': self.group,
                  'ostype': self.ostype,
                  'arch': self.arch,
                  'build': self.build,
                  'buildrelease': self.buildrelease,
                  'repo': self.repo
                }
        
        return output

class Errors:
    
    def __init__(self):
        
        self.error = boo
